<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

class m_website_services_URLService extends f_core_Service
{	
	/**
	 * Retrieve the correct page from the given URL
	 * 
	 * @param string $url
	 * @return m_website_documents_Page
	 */
	public static function getPageFromUrl($url)
	{
        $url = str_replace(URL_ABSOLUTE_WO_HTTP, '', $url);
		$urlParams = explode('/', $url);
		
		// 1 - We get the website ID
		$documentProvider = f_document_Provider::getInstance();
		
		$website = $documentProvider->loadDocuments('website/Website')->whereIsEqual('url', URL_ABSOLUTE_WO_HTTP)->retrieveFirstDocument();

		if(is_null($website))
		{
			throw new Exception('No website with this URL');
		}
        
        f_core_Context::getInstance()->setContext('currentWebsite', $website);

		// 2 - Check if we are in a translated website
		$langs = $website->getTranslationLangs();

		if($urlParams[1] != "" && in_array(strtoupper($urlParams[1]), $langs))
		{
			$website = $documentProvider->getByModelAndUniqueId('website/Website', $website->getUniqueId(), $urlParams[1]);
			$urlWoHost = str_replace('/'.$urlParams[1],'', $url);
		}
		else
		{
			$urlWoHost = $url;
		}

		// 3 - we retrieve the page        

		if($urlWoHost == '') $urlWoHost = '/';

        $page = $documentProvider	    ->loadDocuments('website/Page')
                                        ->whereIsEqual('url', $urlWoHost)
                                        ->byPublicationStatus('PUBLISHED')
                                        ->whereIsEqual('websiteId', $website->getUniqueId())
                                        ->retrieveFirstDocument($website->getLang());

		if(is_null($page))
		{
			$page = self::getExtendedPage($urlWoHost, $website->getUniqueId(), $website->getLang());
		}
	
		if(!is_null($page))
		{
//			$cache->putInCache($cacheKey, array("docId" => $documents[0]->getId(), "docLang" => $documents[0]->getLang()) , 75000);
			return $page;
		}

		return null;
	}

    private static function getExtendedPage($url, $websiteId, $lang)
    {
        $documentProvider = f_document_Provider::getInstance();

        $pos = strrpos($url, '/');

        if($pos == 0) $pos = strlen($url);

        $regexp = substr($url, 0, $pos).'/<.*>';

        $page = $documentProvider   ->loadDocuments('website/Page')
                                    ->whereRegexp('url', '^'.$regexp.'$')
                                    ->byPublicationStatus('PUBLISHED')
                                    ->whereIsEqual('websiteId', $websiteId)
                                    ->retrieveFirstDocument($lang);

        if(is_null($page))
        {
            $page = $documentProvider   ->loadDocuments('website/Page')
                            ->whereRegexp('url', '^/<.*>$')
                            ->whereIsEqual('document_publicationstatus', 'PUBLISHED')
                            ->whereIsEqual('websiteId', $websiteId)
                            ->retrieveFirstDocument($lang);
            $pos = 0;
        }
        
        if(!is_null($page))
        {
            preg_match('/<(.*?)>/', $page->getUrl(true), $matches);
            
            if(isset($matches[1]))
            {
                $model = $matches[1];

                $url = substr($url, $pos+1);
                if($url !== false)
                {
                    $suffix[0]['model'] = $model;
                    $suffix[0]['url'] = $url;

                    f_core_Request::getInstance()->setParameter('urlSuffix', $suffix);
                }
            }
        }

        return $page;
    }
	
	/**
	 * Check if a given url exists into db
	 * 
	 * @param string $url
	 * @return boolean
	 */
	public static function urlExists($url, $websiteId, $lang, $documentModel = 'modules_website/Page')
	{	
        $requete = f_document_Provider::getInstance()->loadDocuments($documentModel)->byPublicationStatus('PUBLISHED')->whereIsEqual('url', $url);
        
        if(!is_null($websiteId))
        {
            $requete = $requete->whereIsEqual('websiteId', $websiteId);
        }

        return $requete->count($lang) >= 1;
	}
}